<template>
  <div class="container-fluid d-flex justify-content-center align-items-center vh-100 bg-primary">
    <div class="card w-25">
      <div class="card-body">
        <h1 class="card-title text-center mb-4">登录页面</h1>
        <form @submit.prevent="handleLogin">
          <div class="mb-3">
            <label for="username" class="form-label">用户名:</label>
            <input type="text" id="username" name="username" class="form-control" />
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">密码:</label>
            <input type="password" id="password" name="password" class="form-control" />
          </div>
          <button type="submit" class="btn btn-primary w-100" :disabled="isLoggingIn">
            {{ isLoggingIn ? '登录中...' : '登录' }}
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user.store';
import { ref } from 'vue';
import { MessageBox } from '../utils/MessageBox';

const store = useUserStore();
const router = useRouter();
const isLoggingIn = ref(false); // 新增：登录状态标识

const handleLogin = async () => {
  const username = document.getElementById('username') as HTMLInputElement;
  const password = document.getElementById('password') as HTMLInputElement;

  if (username && password) {
    isLoggingIn.value = true; // 开始登录，禁用按钮
    try {
      await store.login(username.value, password.value);
      // 登录成功后导航到默认首页
      router.push('/');
    } catch (error) {
      console.error('登录失败:', error);
      MessageBox.alert('登录失败，请检查用户名和密码');
      // 可以在这里添加更多的错误处理逻辑，例如显示错误消息
    } finally {
      isLoggingIn.value = false; // 登录完成，恢复按钮状态
    }
  }
};
</script>

<style scoped>
/* 可以根据需要添加额外的样式 */
</style>
